package cz.ujep.ki.emap;

import java.util.LinkedList;
import java.util.Queue;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONQueue {
	private Queue<JSONObject>  queue;
	private int maxSize;
	
	public JSONQueue(int maxSize) {
		this.queue = new LinkedList<JSONObject>();
		this.maxSize = maxSize;
	}
	
	public JSONQueue(int maxSize, String jsonString) {
		this.queue = new LinkedList<JSONObject>();
		this.maxSize = maxSize;
		JSONArray array;
		try {
			array = new JSONArray(jsonString);
		} catch (JSONException e) {
			Log.e("JsonQueue","Invalid JSONArray");
			return;
		}
		for (int i = 0; i < array.length(); i++) {
			try {
				queue.add(array.getJSONObject(i));
			} catch (JSONException e) {
				Log.e("JsonQueue","Invalid JSONArray");
			}
		}
	}

	public boolean push(JSONObject object) {
		this.queue.add(object);
		if(this.queue.size() > maxSize) {
			this.queue.poll();
			return true;
		}
		else
			return false;
	}
	
	public JSONArray toJSON() {
		return new JSONArray(this.queue);
	}
	
	public void clear() {
		queue.clear();
	}
	
	public boolean empty() {
		return queue.size() == 0;
	}
}
